package com.lincoln.framework;


import com.lincoln.framework.interfaces.BaseDeviceInfo;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务器上下文
 * 此处定义可定义使用的各种class类型,BaseDeviceInfo
 *
 * @author lincoln
 * @date 2018/11/30
 */
@Data
public class ProtocolContextBean {

    /**
     * BaseDeviceInfo的实例类型
     */
    private Class baseDeviceInfoClassType;

    /**
     * 当前线程下绑定的deviceInfo
     */
    private ThreadLocal<BaseDeviceInfo> deviceInfoThreadLocal;

    /**
     * 客户端列表,不同类型的设备放在不同的map中:<deviceType,<clientId,client>>
     */
    private ConcurrentHashMap<Integer, ConcurrentHashMap<String, BaseDeviceInfo>> clients = new ConcurrentHashMap<>();

    /**
     * 没有登陆的客户端会在一定时间后被销毁,可以通过deviceInfo.login()登陆
     */
    private ConcurrentHashMap<String, BaseDeviceInfo> noLoginClients = new ConcurrentHashMap<>();

    /**
     * 初始化
     */
    public void init() {
        deviceInfoThreadLocal = new ThreadLocal<>();
    }

    /**
     * 获取当前设备
     *
     * @return
     */
    public BaseDeviceInfo getDevice() {
        BaseDeviceInfo deviceInfo = deviceInfoThreadLocal.get();
        //第一次请求
        if (deviceInfo == null) {
            try {
                deviceInfo = (BaseDeviceInfo) baseDeviceInfoClassType.newInstance();
                setDevice(deviceInfo);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return deviceInfo;
    }

    /**
     * 设置当前设备
     *
     * @param deviceInfo
     * @return
     */
    public boolean setDevice(BaseDeviceInfo deviceInfo) {
        try {
            deviceInfoThreadLocal.set(deviceInfo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean remove() {
        deviceInfoThreadLocal.get().logout();
        deviceInfoThreadLocal.remove();
        return true;
    }
}
